package com.xb.system.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xb.model.domain.dto.PackageDetailsDTO;
import com.xb.model.domain.entity.PaymentOrder;
import com.xb.model.domain.entity.RechargeRecord;
import com.xb.model.domain.entity.Userinfo;
import com.xb.model.domain.entity.VipPackage;
import com.xb.system.config.PaymentConfig;
import com.xb.system.mapper.db1.PaymentOrderMapper;
import com.xb.system.mapper.db1.UserMapper;
import com.xb.system.service.PaymentService;
import com.xb.system.service.RechargeRecordService;
import com.xb.system.service.VipPackageService;
import com.xb.system.utils.UserContext;
import com.xb.system.utils.WechatPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.concurrent.CompletableFuture;

@Slf4j
@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentOrderMapper, PaymentOrder> implements PaymentService {

    @Autowired
    private PaymentConfig paymentConfig;
    
    @Autowired
    private RechargeRecordService rechargeRecordService;
    
    @Autowired
    private VipPackageService vipPackageService;
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private RestTemplate restTemplate;
    
    @Value("${promotion.callback.url}")
    private String promotionCallbackUrl;
    
    @Value("${promotion.callback.appSecret}")
    private String promotionAppSecret;
    
    private final String GATEWAY_URL = "https://openapi.alipay.com/gateway.do";
    private final String SANDBOX_GATEWAY_URL = "https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "json";
    private final String CHARSET = "UTF-8";
    private final String SIGN_TYPE = "RSA2";

    @Override
    public PaymentOrder createPaymentOrder(Long userId, BigDecimal amount, Integer paymentType, 
                                          String packageType, Integer packagePoints, String packageDuration) {
        // 生成订单号
        String orderNo = generateOrderNo(userId);
        
        PaymentOrder paymentOrder = new PaymentOrder();
        // 如果userId为null，使用0作为匿名用户的标识
        paymentOrder.setUserId(userId != null ? userId : 0L);
        paymentOrder.setOrderNo(orderNo);
        paymentOrder.setAmount(amount);
        paymentOrder.setPaymentType(paymentType);
        paymentOrder.setStatus(0); // 未支付
        paymentOrder.setPackageType(packageType);
        paymentOrder.setPackagePoints(packagePoints);
        paymentOrder.setPackageDuration(packageDuration);
        paymentOrder.setCreateTime(LocalDateTime.now());
        paymentOrder.setUpdateTime(LocalDateTime.now());
        
        // 保存订单
        this.save(paymentOrder);
        
        // 生成支付二维码
        String qrCodeUrl = "";
        if (paymentType == 1) {
            qrCodeUrl = getWechatPayQrCode(orderNo);
        } else if (paymentType == 2) {
            qrCodeUrl = getAlipayPayQrCode(orderNo);
        }
        
        // 更新二维码URL
        if (qrCodeUrl != null && !qrCodeUrl.isEmpty()) {
            paymentOrder.setQrCodeUrl(qrCodeUrl);
            this.updateById(paymentOrder);
        }
        
        return paymentOrder;
    }

    @Override
    public String getWechatPayQrCode(String orderNo) {
        // 获取订单信息
        PaymentOrder order = getOrderByOrderNo(orderNo);
        if (order == null) {
            log.error("订单不存在: {}", orderNo);
            return null;
        }
        
        try {
            // 构建微信支付参数
            Map<String, String> params = new HashMap<>();
            params.put("appid", paymentConfig.getWechatPay().getAppId());
            params.put("mch_id", paymentConfig.getWechatPay().getMchId());
            params.put("nonce_str", WechatPayUtil.generateNonceStr());
            params.put("body", "会员充值-" + order.getPackageType());
            params.put("out_trade_no", order.getOrderNo());
            // 微信支付金额单位为分
            params.put("total_fee", String.valueOf(order.getAmount().multiply(new BigDecimal("100")).intValue()));
            params.put("spbill_create_ip", "127.0.0.1");
            params.put("notify_url", paymentConfig.getWechatPay().getNotifyUrl());
            params.put("trade_type", "NATIVE"); // 扫码支付
            
            // 生成签名
            String sign = WechatPayUtil.generateSign(params, paymentConfig.getWechatPay().getMchKey());
            params.put("sign", sign);
            
            // 调用统一下单接口
            String codeUrl = WechatPayUtil.createUnifiedOrder(params);
            
            if (codeUrl != null) {
                log.info("生成微信支付二维码成功: {}", codeUrl);
                return codeUrl;
            } else {
                log.error("生成微信支付二维码失败");
                return null;
            }
        } catch (Exception e) {
            log.error("生成微信支付二维码异常", e);
            return null;
        }
    }

    @Override
    public String getAlipayPayQrCode(String orderNo) {
        // 获取订单信息
        PaymentOrder order = getOrderByOrderNo(orderNo);
        if (order == null) {
            log.error("订单不存在: {}", orderNo);
            return null;
        }
        
        try {
            log.info("开始生成支付宝支付二维码，订单号: {}", orderNo);
            // 初始化AlipayClient
            String gatewayUrl = paymentConfig.getAlipay().isSandbox() ? SANDBOX_GATEWAY_URL : GATEWAY_URL;
            AlipayClient alipayClient = new DefaultAlipayClient(
                    gatewayUrl,
                    paymentConfig.getAlipay().getAppId(),
                    paymentConfig.getAlipay().getPrivateKey(),
                    FORMAT,
                    CHARSET,
                    paymentConfig.getAlipay().getAlipayPublicKey(),
                    SIGN_TYPE
            );
            
            log.info("支付宝配置信息: gatewayUrl={}, appId={}, privateKey长度={}, alipayPublicKey长度={}", 
                    gatewayUrl, paymentConfig.getAlipay().getAppId(), 
                    paymentConfig.getAlipay().getPrivateKey().length(),
                    paymentConfig.getAlipay().getAlipayPublicKey().length());
            
            // 使用电脑网站支付接口
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            request.setReturnUrl(paymentConfig.getAlipay().getReturnUrl()); // 支付成功后跳转的页面
            request.setNotifyUrl(paymentConfig.getAlipay().getNotifyUrl());
            
            // 构建请求参数
            Map<String, String> bizContent = new HashMap<>();
            bizContent.put("out_trade_no", order.getOrderNo());
            bizContent.put("total_amount", order.getAmount().toString());
            bizContent.put("subject", "会员充值-" + order.getPackageType());
            bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY"); // 电脑网站支付产品码
            bizContent.put("store_id", "JLH_STORE");
            bizContent.put("body", "会员充值服务");
            bizContent.put("timeout_express", "90m");
            
            String bizContentJson = com.alibaba.fastjson2.JSON.toJSONString(bizContent);
            log.info("支付宝请求参数: {}", bizContentJson);
            request.setBizContent(bizContentJson);
            
            // 调用支付宝接口获取支付表单
            String form = alipayClient.pageExecute(request).getBody();
            return form; // 返回表单，前端需要直接显示该表单而非生成二维码
        } catch (AlipayApiException e) {
            log.error("调用支付宝接口异常", e);
            return null;
        }
    }

    @Override
    @Transactional
    public boolean handleWechatPayNotify(Map<String, String> notifyData) {
        try {
            log.info("接收到微信支付回调: {}", notifyData);
            
            // 验证返回状态
            if (!"SUCCESS".equals(notifyData.get("return_code"))) {
                log.error("微信支付回调通知失败: {}", notifyData.get("return_msg"));
                return false;
            }
            
            // 验证签名
            boolean signValid = WechatPayUtil.verifySign(notifyData, paymentConfig.getWechatPay().getMchKey());
            if (!signValid) {
                log.error("微信支付回调签名验证失败");
                return false;
            }
            
            // 验证业务结果
            if (!"SUCCESS".equals(notifyData.get("result_code"))) {
                log.error("微信支付业务结果失败: {}", notifyData.get("err_code_des"));
                return false;
            }
            
            String orderNo = notifyData.get("out_trade_no");
            String transactionId = notifyData.get("transaction_id");
            
            PaymentOrder order = getOrderByOrderNo(orderNo);
            if (order == null) {
                log.error("订单不存在: {}", orderNo);
                return false;
            }
            
            // 判断金额是否一致
            BigDecimal notifyAmount = new BigDecimal(notifyData.get("total_fee")).divide(new BigDecimal(100));
            if (order.getAmount().compareTo(notifyAmount) != 0) {
                log.error("订单金额不匹配: {} != {}", order.getAmount(), notifyAmount);
                return false;
            }
            
            // 更新订单状态
            return updateOrderPaid(order, transactionId);
        } catch (Exception e) {
            log.error("处理微信支付回调失败", e);
            return false;
        }
    }

    @Override
    @Transactional
    public boolean handleAlipayNotify(Map<String, String> notifyData) {
        try {
            // 验证签名等信息
            // TODO: 实际项目中需要验证签名
            
            String orderNo = notifyData.get("out_trade_no");
            String tradeStatus = notifyData.get("trade_status");
            String transactionId = notifyData.get("trade_no");
            
            // 只处理支付成功的回调
            if (!"TRADE_SUCCESS".equals(tradeStatus)) {
                return true;
            }
            
            PaymentOrder order = getOrderByOrderNo(orderNo);
            if (order == null) {
                log.error("订单不存在: {}", orderNo);
                return false;
            }
            
            // 判断金额是否一致
            BigDecimal notifyAmount = new BigDecimal(notifyData.get("total_amount"));
            if (order.getAmount().compareTo(notifyAmount) != 0) {
                log.error("订单金额不匹配: {} != {}", order.getAmount(), notifyAmount);
                return false;
            }
            
            // 更新订单状态
            return updateOrderPaid(order, transactionId);
        } catch (Exception e) {
            log.error("处理支付宝回调失败", e);
            return false;
        }
    }

    @Override
    public PaymentOrder queryPaymentOrder(String orderNo) {
        return getOrderByOrderNo(orderNo);
    }

    @Override
    public boolean cancelPaymentOrder(String orderNo) {
        PaymentOrder order = getOrderByOrderNo(orderNo);
        if (order == null) {
            return false;
        }
        
        // 只有未支付的订单可以取消
        if (order.getStatus() != 0) {
            return false;
        }
        
        // 更新订单状态为已取消
        LambdaUpdateWrapper<PaymentOrder> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(PaymentOrder::getOrderNo, orderNo)
                    .set(PaymentOrder::getStatus, 3)
                    .set(PaymentOrder::getUpdateTime, LocalDateTime.now());
        
        return this.update(updateWrapper);
    }

    @Override
    public List<PaymentOrder> getUserPaymentRecords(Long userId) {
        if (userId == null) {
            userId = UserContext.getUserId();
        }
        
        LambdaQueryWrapper<PaymentOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaymentOrder::getUserId, userId)
                   .eq(PaymentOrder::getIsDeleted, 0)
                   .orderByDesc(PaymentOrder::getCreateTime);
        
        return this.list(queryWrapper);
    }
    
    /**
     * 根据订单号获取订单
     */
    private PaymentOrder getOrderByOrderNo(String orderNo) {
        LambdaQueryWrapper<PaymentOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaymentOrder::getOrderNo, orderNo)
                   .eq(PaymentOrder::getIsDeleted, 0);
        
        return this.getOne(queryWrapper);
    }
    
    /**
     * 生成订单号
     */
    private String generateOrderNo(Long userId) {
        // 时间戳 + 用户ID后4位 + 4位随机数
        LocalDateTime now = LocalDateTime.now();
        String timestamp = String.valueOf(now.toEpochSecond(ZoneOffset.UTC));
        // 处理userId为null的情况，使用0作为默认值
        long userIdValue = (userId != null) ? userId : 0L;
        String userIdStr = String.format("%04d", userIdValue % 10000);
        String randomNum = String.format("%04d", new Random().nextInt(10000));
        
        return timestamp + userIdStr + randomNum;
    }
    
    /**
     * 更新订单为已支付状态并处理充值
     */
    @Transactional
    public boolean updateOrderPaid(PaymentOrder order, String transactionId) {
        return updateOrderPaid(order, transactionId, false);
    }
    
    /**
     * 更新订单为已支付状态并处理充值
     * @param order 订单
     * @param transactionId 交易ID
     * @param forceProcess 是否强制处理（用于补偿机制，即使订单已处理也重新处理）
     */
    @Transactional
    public boolean updateOrderPaid(PaymentOrder order, String transactionId, boolean forceProcess) {
        try {
            log.info("开始处理订单支付成功: orderNo={}, userId={}, amount={}, forceProcess={}", 
                    order.getOrderNo(), order.getUserId(), order.getAmount(), forceProcess);
            
            // 检查订单状态，避免重复处理（除非是强制处理）
            if (!forceProcess && order.getStatus() == 1) {
                log.info("订单已处理，无需重复处理: {}", order.getOrderNo());
                return true;
            }
            
            // 获取userId（可能为0，但也要处理，后续可以通过补偿机制关联到真实用户）
            Long userId = order.getUserId();
            if (userId == null) {
                log.warn("订单userId为null，使用0作为默认值: orderNo={}", order.getOrderNo());
                userId = 0L;
            }
            
            // 1. 更新订单状态
            order.setStatus(1); // 已支付
            order.setTransactionId(transactionId);
            order.setPayTime(LocalDateTime.now());
            order.setUpdateTime(LocalDateTime.now());
            this.updateById(order);
            log.info("订单状态已更新为已支付: orderNo={}", order.getOrderNo());
            
            // 如果userId为0，说明是匿名用户订单，跳过创建充值记录和套餐
            // 这些订单会在用户登录后通过补偿机制处理（在VipPackageController.getUserPackage中）
            if (userId == 0) {
                log.info("匿名用户订单，跳过创建充值记录和套餐，等待用户登录后补偿处理: orderNo={}, userId=0", order.getOrderNo());
                return true;
            }
            
            // 2. 创建充值记录
            try {
                RechargeRecord rechargeRecord = new RechargeRecord();
                rechargeRecord.setUserId(userId);
                
                // 查询用户手机号
                String userPhone = "";
                String inviterId = null;
                try {
                    Userinfo user = userMapper.selectById(userId);
                    if (user != null) {
                        userPhone = user.getPhone();
                        rechargeRecord.setPhone(userPhone);
                        inviterId = user.getInviterId(); // 获取邀请人ID
                        log.info("获取用户信息成功: userId={}, phone={}, inviterId={}", userId, userPhone, inviterId);
                    } else {
                        log.warn("用户不存在: userId={}", userId);
                        // 如果无法获取手机号，设置一个默认值或者用户ID作为备用
                        rechargeRecord.setPhone(String.valueOf(userId));
                    }
                } catch (Exception e) {
                    log.error("获取用户信息失败: userId={}", userId, e);
                    // 设置默认值
                    rechargeRecord.setPhone(String.valueOf(userId));
                }
                
                rechargeRecord.setAmount(order.getPackagePoints());
                
                // 构建充值套餐详情
                PackageDetailsDTO packageDetails = new PackageDetailsDTO();
                packageDetails.setPrice(order.getAmount().intValue());
                packageDetails.setPoints(order.getPackagePoints());
                packageDetails.setDuration(order.getPackageDuration());
                packageDetails.setBypassCheck(false); // 普通用户充值不允许绕过检查
                packageDetails.setAllowAnyUser(false); // 普通用户充值不允许任何用户使用
                
                // 转换为JSON字符串
                try {
                    com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
                    rechargeRecord.setPackageDetailsJson(mapper.writeValueAsString(packageDetails));
                } catch (Exception e) {
                    log.error("序列化PackageDetails失败", e);
                }
                
                rechargeRecord.setTransferTime(order.getPayTime());
                // 设置创建时间和更新时间，避免null值
                LocalDateTime now = LocalDateTime.now();
                rechargeRecord.setCreateTime(now);
                rechargeRecord.setUpdateTime(now);
                rechargeRecordService.save(rechargeRecord);
                log.info("充值记录创建成功: userId={}, amount={}", userId, order.getPackagePoints());
            } catch (Exception e) {
                log.error("创建充值记录失败: userId={}, orderNo={}", userId, order.getOrderNo(), e);
                // 继续处理套餐，不中断流程
            }
            
            // 3. 更新会员套餐
            try {
                LocalDateTime now = LocalDateTime.now();
                VipPackage vipPackage = vipPackageService.getUserPackage(userId);
                if (vipPackage == null) {
                    // 新用户，创建套餐
                    log.info("创建新用户套餐: userId={}, packageType={}, points={}", 
                            userId, order.getPackageType(), order.getPackagePoints());
                    vipPackage = new VipPackage();
                    vipPackage.setUserId(userId);
                    vipPackage.setPackageType(order.getPackageType());
                    vipPackage.setTotalQuota(order.getPackagePoints());
                    vipPackage.setUsedQuota(0);
                    // 处理套餐时间
                    vipPackage.setStartTime(now);
                    // 解析时长，计算结束时间
                    String duration = order.getPackageDuration();
                    int days = 30; // 默认30天
                    try {
                        String daysStr = duration.replaceAll("[^0-9]", "");
                        days = Integer.parseInt(daysStr);
                    } catch (Exception e) {
                        log.warn("解析套餐时长失败，使用默认值: {}", duration);
                    }
                    
                    vipPackage.setEndTime(now.plusDays(days));
                    // 设置创建时间和更新时间
                    vipPackage.setCreateTime(now);
                    vipPackage.setUpdateTime(now);
                    // 重要：设置 isDeleted 为 0，否则查询时找不到
                    vipPackage.setIsDeleted(0);
                    
                    // 保存套餐，并检查是否成功
                    boolean saveResult = vipPackageService.save(vipPackage);
                    if (!saveResult) {
                        log.error("套餐保存失败，save方法返回false: userId={}", userId);
                        throw new RuntimeException("套餐保存失败");
                    }
                    
                    // 验证套餐是否真的保存成功
                    VipPackage savedPackage = vipPackageService.getUserPackage(userId);
                    if (savedPackage == null) {
                        log.error("套餐保存后查询不到，可能保存失败: userId={}", userId);
                        throw new RuntimeException("套餐保存后查询不到");
                    }
                    
                    log.info("新用户套餐创建成功: userId={}, packageId={}, totalQuota={}, endTime={}, isDeleted={}", 
                            userId, savedPackage.getId(), savedPackage.getTotalQuota(), savedPackage.getEndTime(), savedPackage.getIsDeleted());
                } else {
                    // 续费用户，更新套餐
                    log.info("更新用户套餐: userId={}, packageType={}, points={}", 
                            userId, order.getPackageType(), order.getPackagePoints());
                    // 处理套餐时间
                    LocalDateTime endTime;
                    if (vipPackage.getEndTime().isAfter(LocalDateTime.now())) {
                        // 当前套餐还未到期，在原到期时间基础上增加天数
                        endTime = vipPackage.getEndTime();
                    } else {
                        // 当前套餐已到期，从现在开始计算
                        endTime = LocalDateTime.now();
                    }
                    
                    // 解析时长，计算新的结束时间
                    String duration = order.getPackageDuration();
                    int days = 30; // 默认30天
                    try {
                        String daysStr = duration.replaceAll("[^0-9]", "");
                        days = Integer.parseInt(daysStr);
                    } catch (Exception e) {
                        log.warn("解析套餐时长失败，使用默认值: {}", duration);
                    }
                    
                    // 更新套餐
                    vipPackage.setTotalQuota(vipPackage.getTotalQuota() + order.getPackagePoints());
                    vipPackage.setEndTime(endTime.plusDays(days));
                    // 更新套餐名称
                    vipPackage.setPackageType(order.getPackageType());
                    // 更新更新时间
                    vipPackage.setUpdateTime(LocalDateTime.now());
                    // 确保 isDeleted 为 0
                    vipPackage.setIsDeleted(0);
                    
                    // 更新套餐，并检查是否成功
                    boolean updateResult = vipPackageService.updateById(vipPackage);
                    if (!updateResult) {
                        log.error("套餐更新失败，updateById方法返回false: userId={}, packageId={}", userId, vipPackage.getId());
                        throw new RuntimeException("套餐更新失败");
                    }
                    
                    // 验证套餐是否真的更新成功
                    VipPackage updatedPackage = vipPackageService.getUserPackage(userId);
                    if (updatedPackage == null) {
                        log.error("套餐更新后查询不到，可能更新失败: userId={}", userId);
                        throw new RuntimeException("套餐更新后查询不到");
                    }
                    
                    log.info("用户套餐更新成功: userId={}, packageId={}, totalQuota={}, endTime={}, isDeleted={}", 
                            userId, updatedPackage.getId(), updatedPackage.getTotalQuota(), updatedPackage.getEndTime(), updatedPackage.getIsDeleted());
                }
            } catch (Exception e) {
                log.error("更新会员套餐失败: userId={}, orderNo={}, 异常详情: {}", userId, order.getOrderNo(), e.getMessage(), e);
                // 抛出异常，让事务回滚，确保数据一致性
                throw new RuntimeException("更新会员套餐失败: " + e.getMessage(), e);
            }
            
            // 4. 如果有邀请人，通知推广系统充值成功
            try {
                String userPhone = "";
                String inviterId = null;
                Userinfo user = userMapper.selectById(userId);
                if (user != null) {
                    userPhone = user.getPhone();
                    inviterId = user.getInviterId();
                }
                if (inviterId != null && !inviterId.isEmpty() && !userPhone.isEmpty()) {
                    notifyPromotionSystemForRecharge(inviterId, userPhone, order.getAmount(), LocalDateTime.now());
                }
            } catch (Exception e) {
                log.warn("通知推广系统失败", e);
                // 不影响主流程
            }
            
            log.info("订单支付处理完成: orderNo={}, userId={}", order.getOrderNo(), userId);
            return true;
        } catch (Exception e) {
            log.error("处理订单支付失败: orderNo={}, userId={}", order.getOrderNo(), order.getUserId(), e);
            return false;
        }
    }
    
    /**
     * 通知推广系统用户充值成功
     * @param inviterId 邀请人ID
     * @param userPhone 用户手机号
     * @param amount 充值金额
     * @param rechargeTime 充值时间
     */
    private void notifyPromotionSystemForRecharge(String inviterId, String userPhone, BigDecimal amount, LocalDateTime rechargeTime) {
        try {
            // 构建请求参数
            Map<String, Object> params = new HashMap<>();
            params.put("inviterCode", inviterId);
            params.put("inviteePhone", userPhone);
            params.put("rechargeAmount", amount);
            params.put("rechargeTime", rechargeTime);
            params.put("appId", "jlh"); // 当前应用的标识
            
            // 添加时间戳
            long timestamp = System.currentTimeMillis();
            params.put("timestamp", timestamp);
            
            // 生成签名
            String signContent = inviterId + userPhone + amount.toString() + "jlh" + timestamp + promotionAppSecret;
            String sign = org.springframework.util.DigestUtils.md5DigestAsHex(signContent.getBytes());
            params.put("sign", sign);
            
            // 异步执行回调，不阻塞主流程
            CompletableFuture.runAsync(() -> {
                try {
                    // 直接调用推广系统API
                    HttpHeaders headers = new HttpHeaders();
                    headers.setContentType(MediaType.APPLICATION_JSON);
                    HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(params, headers);
                    
                    // 这里使用不同的URL，可以根据实际情况调整
                    String rechargeCallbackUrl = promotionCallbackUrl.replace("/callback", "/recharge-callback");
                    String result = restTemplate.postForObject(rechargeCallbackUrl, requestEntity, String.class);
                    log.info("推广系统充值回调结果: {}", result);
                } catch (Exception e) {
                    log.error("回调推广系统充值接口出错: {}", e.getMessage(), e);
                }
            });
        } catch (Exception e) {
            log.error("构建推广系统充值回调请求出错: {}", e.getMessage(), e);
        }
    }
    
    @Override
    public boolean hasUserPurchasedSpecialPackage(Long userId) {
        // 如果userId为null，无法查询，返回false
        if (userId == null) {
            return false;
        }
        
        // 查询用户是否有已支付成功的19.9套餐订单
        LambdaQueryWrapper<PaymentOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaymentOrder::getUserId, userId)
                    .eq(PaymentOrder::getStatus, 1) // 状态为已支付
                    .eq(PaymentOrder::getAmount, new BigDecimal("19.9")); // 金额为19.9
        
        long count = this.count(queryWrapper);
        return count > 0;
    }
    
    @Override
    public boolean compensateOrder(String orderNo) {
        try {
            log.info("开始补偿处理订单: orderNo={}", orderNo);
            PaymentOrder order = getOrderByOrderNo(orderNo);
            if (order == null) {
                log.error("订单不存在: orderNo={}", orderNo);
                return false;
            }
            
            // 只处理已支付的订单
            if (order.getStatus() != 1) {
                log.warn("订单状态不是已支付，无法补偿处理: orderNo={}, status={}", orderNo, order.getStatus());
                return false;
            }
            
            // 使用订单的transactionId，如果没有则使用补偿标识
            String transactionId = order.getTransactionId() != null ? 
                    order.getTransactionId() : "COMPENSATE_" + orderNo;
            
            // 调用updateOrderPaid处理订单，强制处理（即使订单已处理也重新处理）
            return updateOrderPaid(order, transactionId, true);
        } catch (Exception e) {
            log.error("补偿处理订单失败: orderNo={}", orderNo, e);
            return false;
        }
    }
    
    @Override
    public boolean updateOrder(PaymentOrder order) {
        return this.updateById(order);
    }
}